//
//  ShoppingCarViewController.m
//  NewApp
//
//  Created by  on 12-6-15.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "ShoppingCarViewController.h"
#import "CustomTableCellShopCar.h"
#import "ProductData.h"
#import "ShopChecksViewController.h"
#import "ChecksEndViewController.h"

@interface ShoppingCarViewController ()

@end

@implementation ShoppingCarViewController
@synthesize pageType;
@synthesize selectProducts;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [scrollView setFrame:CGRectMake(0, 118, 320, 480)];
    [scrollView setContentSize:CGSizeMake(320, 1100)];
    [scrollView setBackgroundColor:[UIColor grayColor]];
    [scrollView setScrollEnabled:YES];
    
    fdCop.delegate = self;
    fdSearch.delegate = self;
    fdEmail.delegate = self;
    fdAddress.delegate = self;
    fdFax.delegate = self;
    fdTel.delegate = self;
    fdMem.delegate = self;
    fdName.delegate = self;
    activeField.delegate = self;
    
    
    [shopTable setFrame:CGRectMake(0, 0, 320, 230)];
    [shopTable setBackgroundColor:[UIColor clearColor]];
    [shopTable setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    shopTable.delegate = self;
    shopTable.dataSource = self;
    
    [imgTotalBg setFrame:CGRectMake(0, 273, 320, 50)];
    [lblTotal setFrame:CGRectMake(0, 278, 320, 40)];
    
    if (pageType == PAGE_TYPE_SHOP) {
        requestType = REQUEST_TYPE_SHOPCAR;
        if ((selectProducts == NULL) || [selectProducts isEqualToString:@""]) {
            selectProducts = @"11,5x9,3x10,1";            
        }
        [self.engine shoppingCartInfos:selectProducts];
        
        [btConfirm setTitle:@"我要結帳" forState:UIControlStateNormal];

    }else {
        
        requestType = REQUEST_TYPE_QUERYCAR;
        if ((selectProducts == NULL) || [selectProducts isEqualToString:@""]) {
            
            selectProducts = @"11,5x9,3x10,1";            
        }
        [self.engine queryCartInfos:selectProducts];
        
        [btConfirm setTitle:@"我要詢價" forState:UIControlStateNormal];
    }

    
    [self registerForKeyboardNotifications];

}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

#pragma mark - UITextField Delegate  
-(void)textFieldDidBeginEditing:(UITextField *)textField {  
    
    activeField = textField;  
}  

-(void)textFieldDidEndEditing:(UITextField *)textField {  
    activeField = nil;  
}  

-(BOOL)textFieldShouldReturn:(UITextField *)textField {  
    [textField resignFirstResponder];  
    return YES;  
}

// Call this method somewhere in your view controller setup code.  
- (void)registerForKeyboardNotifications {
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasShown:)
                                                 name:UIKeyboardDidShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasHidden:)
                                                 name:UIKeyboardDidHideNotification object:nil];
}

// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification {
    if (keyboardShown)
        return;
    
    NSDictionary* info = [aNotification userInfo];
    
    // Get the size of the keyboard.
    NSValue* aValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGSize keyboardSize = [aValue CGRectValue].size;
    
    // Resize the scroll view (which is the root view of the window)
    CGRect viewFrame = [scrollView frame];
    viewFrame.size.height -= keyboardSize.height;
    scrollView.frame = viewFrame;
    
    // Scroll the active text field into view.
    CGRect textFieldRect = [activeField frame];
    [scrollView scrollRectToVisible:textFieldRect animated:YES];

    
    keyboardShown = YES;
}

// Called when the UIKeyboardDidHideNotification is sent
- (void)keyboardWasHidden:(NSNotification*)aNotification {
    NSDictionary* info = [aNotification userInfo];
    
    // Get the size of the keyboard.
    NSValue* aValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGSize keyboardSize = [aValue CGRectValue].size;
    
    // Reset the height of the scroll view to its original value
    CGRect viewFrame = [scrollView frame];
    viewFrame.size.height += keyboardSize.height;
    scrollView.frame = viewFrame;
    
    keyboardShown = NO;
}


#pragma mark - 
#pragma mark - event methods
-(IBAction)toCash:(id)sender{

    if (pageType == PAGE_TYPE_SHOP) {
        requestType = REQUEST_TYPE_SHOPCHECK;
        [self.engine shopChecksInfos:selectProducts a1:fdName.text a2:fdTel.text a3:fdAddress.text a4:fdEmail.text a5:fdMem.text a0:@"1"];

    }else {
        requestType = REQUEST_TYPE_QUERYEND;
        [self.engine queryEndInfos:selectProducts a1:fdName.text a2:fdTel.text a3:fdAddress.text a4:fdEmail.text a5:fdMem.text a0:@"1"];

    }

}

-(IBAction)toSearch:(id)sender{


}



#pragma mark -
#pragma mark - Private methods

- (void) requestDidFinished:(RequestEngine *)reqEngine withObject:(id)object {
    if (requestType == REQUEST_TYPE_SHOPCAR) {
        if ([object isKindOfClass:[NSDictionary class]]) {
            NSDictionary *result = (NSDictionary *) object;
            [result retain];
            
            self.titleLabel.text = [result objectForKey:@"top_title"];
            NSString *freight = [result objectForKey:@"freight"];
            NSString *subtotal = [result objectForKey:@"subtotal"];
            NSString *total = [result objectForKey:@"total"];
            lblTotal.text = [NSString stringWithFormat:@"小計:$%@/運費:$%@/統計:$%@",subtotal,freight,total];
            NSArray *shopcarArray = [[result objectForKey:@"data"] retain];
            dataArray = [[NSMutableArray alloc] init];
            
            for (NSDictionary *dic in shopcarArray) {
                ShopCarEntity *product = [[ShopCarEntity alloc] initWithDictionary:dic];
                [dataArray addObject:product];
            }
            
            [shopTable reloadData];
            [shopcarArray release];
            [result release];
        }

    }else if(requestType == REQUEST_TYPE_SHOPCHECK){
        
        if ([object isKindOfClass:[NSDictionary class]]) {
            NSDictionary *result = (NSDictionary *) object;
            [result retain];
            
            NSString *status = [result objectForKey:@"status"];
            //NSString *msg = [result objectForKey:@"msg"];
            NSString *order_id = [result objectForKey:@"order_id"];

            if ([status isEqualToString:@"1"]) {
                ShopChecksViewController *vctrl = [[ShopChecksViewController alloc] init];    
                vctrl.order_id = [order_id retain];
                vctrl.titleText = [result objectForKey:@"top_title"];
                [self.navigationController pushViewController:vctrl animated:YES];
                [vctrl release];
            }
            
            [result release];
        }
    }else if(requestType == REQUEST_TYPE_QUERYEND){
        if ([object isKindOfClass:[NSDictionary class]]) {
            NSDictionary *result = (NSDictionary *) object;
            [result retain];
            
            NSString *status = [result objectForKey:@"status"];
            NSString *msg = [result objectForKey:@"msg"];
            // NSString *order_id = [result objectForKey:@"order_id"];
            
            if ([status isEqualToString:@"1"]) {
                
                ChecksEndViewController *vctrl = [[ChecksEndViewController alloc] init];
                vctrl.titleText = [result objectForKey:@"top_title"];
                vctrl.msg = [msg retain];
                [self.navigationController pushViewController:vctrl animated:YES];
                [vctrl release];
            }
            
            [result release];
        }

    }else  if (requestType == REQUEST_TYPE_QUERYCAR) {
        if ([object isKindOfClass:[NSDictionary class]]) {
            NSDictionary *result = (NSDictionary *) object;
            [result retain];
            
            self.titleLabel.text = [result objectForKey:@"top_title"];
            NSString *freight = [result objectForKey:@"freight"];
            NSString *subtotal = [result objectForKey:@"subtotal"];
            NSString *total = [result objectForKey:@"total"];
            lblTotal.text = [NSString stringWithFormat:@"小計:$%@/運費:$%@/統計:$%@",subtotal,freight,total];
            NSArray *shopcarArray = [[result objectForKey:@"data"] retain];
            dataArray = [[NSMutableArray alloc] init];
            
            for (NSDictionary *dic in shopcarArray) {
                ShopCarEntity *product = [[ShopCarEntity alloc] initWithDictionary:dic];
                [dataArray addObject:product];
            }
            
            [shopTable reloadData];
            [shopcarArray release];
            [result release];
        }
        
    }
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 90.0;    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [dataArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{    
    static NSString *CellIdentifier = @"Cell";
    CustomTableCellShopCar *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
 
    if (dataArray == NULL || [dataArray count]<1) {
        return cell;
    }
    
    if (cell == nil)
    {
        cell = [[[CustomTableCellShopCar alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        
        ShopCarEntity *product = [dataArray objectAtIndex:indexPath.row];
        
        [cell.backgroundView setFrame:CGRectMake(0, 0, 320, 90)];
        cell.backgroundColor=[UIColor clearColor];
        if (indexPath.row % 2 == 0 ) {
            cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"news_list_B_item_bg_1.png"]]; 
        }else {
            cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"news_list_B_item_bg_2.png"]];
        }
        
        [cell setContentWithImage:product.img productNO:product.item_no title:product.item_name number:product.num subtotal:product.price];
        
        UIButton *btDelete = [[UIButton buttonWithType:UIButtonTypeCustom] autorelease];
        [btDelete setFrame:CGRectMake(300, 58, 16, 16)];
        [btDelete setImage:[UIImage imageNamed:@"delete_icon"] forState:UIControlStateNormal];
        
        [btDelete addTarget:self action:@selector(deleteCell:) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:btDelete];
    }
    // Configure the cell...
    
    return cell;
}


-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{


}

-(void) deleteCell:(id)sender{

    UIButton *button = (UIButton *)sender; 
    UITableViewCell *cell = (UITableViewCell *)[button superview]; 
    int row = [shopTable indexPathForCell:cell].row; 
    
    NSLog(@"-----%d",row);
    
    for (ShopCarEntity *info in dataArray) {
        NSLog(@"======%@",info.item_name);
    }
    
    [dataArray removeObjectAtIndex:row];
    [shopTable deleteRowsAtIndexPaths:[NSArray arrayWithObject:[shopTable indexPathForCell:cell]] withRowAnimation:UITableViewRowAnimationTop];
    
}


@end
